package com.zxd.interview.conrruentbook;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.stream.IntStream;

/**
 * 模拟最多允许两个线程进行工作的场景
 */
public class SemaphoreTest2 {

    public static void main(String[] args){
        Semaphore semaphore = new Semaphore(2);
        // 6个线程执行，最多允许2个线程可以同时工作，其他线程要进行等待
        ExecutorService threadPool = Executors.newFixedThreadPool(6);
        IntStream.range(0, 6).forEach((i) -> {
            threadPool.submit(new SemaphoreTask(semaphore));
        });
        threadPool.shutdown();
    }

    /**
     * 信号量任务
     */
    private static class SemaphoreTask implements Runnable {
        private Semaphore semaphore;

        public SemaphoreTask(Semaphore semaphore) {
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            try {
                // 获取信号量
                semaphore.acquire();
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName() + "--执行方法--" + new Date());
                // 释放
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
